#include <iostream>
#include <unistd.h>
#include <cstdlib>  //stdlib
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

//写
void Writer(int wfd)
{
    string str = "hello i am chlid";
    pid_t self = getpid();
    int num = 0;

    char buff[1024];
    while (true)
    {
       // buff[0] = 0;  //字符串清空,提醒阅读的人,这个数组当字符串
        num++;
        //snprintf(buff, sizeof(buff), "%s-%d-%d", str.c_str(), self, num);
       // cout << buff << endl;
       //发送给父进程
       // write(wfd, buff, strlen(buff));  //不用加1,文件不遵守c语言
        char ch = 'c';
        write(wfd, &ch, 1);
        cout << num << endl;
        if (num > 5)
        {
            break;
        }
        sleep(1);
    }
    close(wfd);
}

//读
void Reader(int rfd)
{
    char buff[1024];
    while (true)
    {
        buff[0] = 0;
        ssize_t n = read(rfd, buff, sizeof(buff));
        if (n > 0)
        {
            buff[n] = 0; //c串格式读
            //cout << "父进程读到消息[" << getpid() << "]: " << buff << endl;
     
        }
        if (n == 0)
        {
            cout << "读到结尾" << endl;
            break;
        }
    }
}

//子进程写 父进程读
int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    
    //出错
    if (n < 0)
    {
        return 1;
    }

   // cout << "pfd[0]:" << pipefd[0] << ",pfd[1]:" << pipefd[1] << endl;

    pid_t id = fork();
    if (id < 0)
    {
        return 2;
    }
    else if (id == 0)
    {
        //子进程写
        //关闭读
        close(pipefd[0]);
        //IPC code
        Writer(pipefd[1]);
        // 操作完关闭写
       // close(pipefd[1]);
        exit(0);
    }

    //父进程读,关闭写
    close(pipefd[1]);
    //IPC code
    Reader(pipefd[0]);
    pid_t rid = waitpid(id, nullptr, 0);
    if (rid < 0)
    {
        return 3;
    }
    // 操作完关闭
    close(pipefd[0]);
}